<template>
  <div>
    <!-- 
        1.如果给el-form添加了label-width,那么el-form-item会继承这个宽度
    -->
    <el-form
      ref="form"
      label-width="80px"
      :inline="false"
      size="normal"
      :model="spu"
    >
      <el-form-item label="Spu名称">
        <el-input placeholder="Spu名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select
          placeholder="请选择品牌"
          clearable
          filterable
          v-model="spu.tmId"
        >
          <el-option
            v-for="(tm, index) in tradeMarkList"
            :key="tm.id"
            :label="tm.tmName"
            :value="tm.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Spu描述">
        <el-input
          placeholder="Spu描述"
          type="textarea"
          rows="4"
          v-model="spu.description"
        ></el-input>
      </el-form-item>
      <el-form-item label="Spu图片">
        <!-- 
          1.list-style:文件列表的类型
          2.on-preview:图片预览的时候触发,实现预览功能
          3.on-remove:删除图片的时候触发
          4.action:图片上传的地址,记得前缀加上/dev-api,否则会有跨域的问题
          5.file-list:照片墙需要展示的数据(数组,数组里面的元素务必要含有name和url属性,否则图片无法显示)
         -->
        <el-upload
          action="/dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :file-list="spuImageList"
          :on-success="handleSuccess"
        >
          <!-- 图片上传中的+号 -->
          <i class="el-icon-plus"></i>
        </el-upload>
        <!-- 实现图片预览 -->
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          :placeholder="`还有${unSelectSaleAttr.length}未选择`"
          v-model="attrIdAndAttrName"
        >
          <el-option
            v-for="(unSelect, index) in unSelectSaleAttr"
            :key="unSelect.id"
            :label="unSelect.name"
            :value="`${unSelect.id}:${unSelect.name}`"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <!-- 展示当前spu属于自己的销售属性 -->
        <el-table border style="100%" :data="spu.spuSaleAttrList">
          <el-table-column
            label="序号"
            type="index"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column label="属性名" prop="saleAttrName">
          </el-table-column>
          <el-table-column label="属性值名称列表">
            <template slot-scope="{ row, $index }">
              <!-- 
                1.closable:x按钮
                2.disable-transitions:点x的时候能不能使用过度动画
                3.close:点击x时的回调函数
               -->
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="row.spuSaleAttrValueList.splice(index, 1)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>

              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="addSaleAttrValue(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
                icon="el-icon-delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  props: {},
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      // 存储Spu信息属性,初始化时是一个空对象,修改spu时,会向服务器发送请求,从而将获取到的数据赋值给spu,从而
      // 也可以用来收集数据,但是添加spu的时候,并没有向服务器发送请求,此时spu是一个空对象,那么数据收集到spu,
      // spu应该有哪些字段?此时原始的spu不应该为空对象,为了满足添加的需要,应该在spu中添加需要的字段名
      spu: {
        category3Id: 0,
        description: "string",
        // 收集spu图片信息
        spuImageList: [
          {
            id: 0,
            imgName: "string",
            imgUrl: "string",
            spuId: 0,
          },
        ],
        spuName: "",
        // 品牌ID
        tmId: 0,
        // 平台属性和属性值的收集
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "string",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "string",
                saleAttrName: "string",
                saleAttrValueName: "string",
                spuId: 0,
              },
            ],
          },
        ],
      },
      // 存储品牌信息
      tradeMarkList: [],
      // 存储Spu图片
      spuImageList: [],
      saleAttrList: [],
      attrIdAndAttrName: "",
    };
  },
  methods: {
    async addOrUpdateSpu() {
      // 整理参数
      this.spu.spuImageList = this.spuImageList.map((item) => {
        return {
          imageName: item.name,
          // 对于新增的图片来说,imageUrl不能使用item中的url,因为那是本地图片的url,得使用服务器response返回的url
          // 而原来就有的图片可以使用item中的url
          imageUrl: (item.response && item.response.data) || item.url,
        };
      });
      let result = await this.$API.Spu.reqAddOrUpdateSpu(this.spu);
      if ((result.code = 200)) {
        this.$message.success("保存成功");
        // 通知父组件回到场景0的状态
        this.$emit("changeScene", {
          scene: 0,
          flag: this.spu.id ? "修改" : "添加",
        });
        this.clearAllData();
      }
    },
    clearAllData() {
      this.tradeMarkList = [];
      this.spuImageList = [];
      this.saleAttrList = [];
      this.attrIdAndAttrName = "";
      this.spu = {
        category3Id: 0,
        description: "string",
        spuImageList: [
          {
            id: 0,
            imgName: "string",
            imgUrl: "string",
            spuId: 0,
          },
        ],
        spuName: "",
        tmId: 0,
        spuSaleAttrList: [
          {
            baseSaleAttrId: 0,
            id: 0,
            saleAttrName: "string",
            spuId: 0,
            spuSaleAttrValueList: [
              {
                baseSaleAttrId: 0,
                id: 0,
                isChecked: "string",
                saleAttrName: "string",
                saleAttrValueName: "string",
                spuId: 0,
              },
            ],
          },
        ],
      };
      this.dialogImageUrl = "";
      this.dialogVisible = false;
    },
    handleInputConfirm(row) {
      const { baseSaleAttrId, inputValue } = row;
      // 属性值不能为空
      if (inputValue.trim() == "") {
        this.$message.error("属性值不能为空");
        return;
      }
      // 属性值不能重复
      let result = row.spuSaleAttrValueList.every((element) => {
        return element.saleAttrValueName != inputValue;
      });
      if (!result) {
        return;
      }
      let newSaleAttrValue = { baseSaleAttrId, saleAttrValueName: inputValue };
      row.spuSaleAttrValueList.push(newSaleAttrValue);
      row.inputVisible = false;
    },
    addSaleAttrValue(row) {
      // 挂载在销售属性身上的响应式数据inputVisible,控制button和input的切换
      this.$set(row, "inputVisible", true);
      // 通过响应式数据inputValue字段收集新增的销售属性值
      this.$set(row, "inputValue", "");
    },
    // 添加新的销售属性
    addSaleAttr() {
      // 将收集到的数据进行分割
      const [baseSaleAttrId, saleAttrValueName] =
        this.attrIdAndAttrName.split(":");
      // 向spu对象的数组spuSaleAttrList添加收集到的数据
      let newSaleAttr = {
        baseSaleAttrId,
        saleAttrValueName,
        spuSaleAttrValueList: [],
      };
      this.spu.spuSaleAttrList.push(newSaleAttr);
      this.attrIdAndAttrName = "";
    },
    // file:上传成功的那张图,fileList:上传成功后的所有图片信息,response:服务器的返回信息
    handleSuccess(response, file, fileList) {
      this.spuImageList = fileList;
    },
    // 照片墙删除图片的时候触发,file:是我们删除的那张图片,fileList:剩余的其他的图片
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },

    handlePictureCardPreview(file) {
      // 收集相应的图片地址,从而放到对话框中大图展示出来
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    async initSpuData(spu) {
      let spuResult = await this.$API.Spu.reqSpu(spu.id);
      if (spuResult.code == 200) {
        this.spu = spuResult.data;
      }
      let tradeMarkResult = await this.$API.Spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList.tradeMarkResult.data;
      }
      let spuImageResult = await this.$API.Spu.reqSpuImageList(spu.id);
      if (spuImageResult.code == 200) {
        let listArr = spuImageResult.data;
        listArr.forEach((element) => {
          element.name = element.imgName;
          element.url = element.imgUrl;
        });
        this.spuImageList = listArr;
      }
      let saleResult = await this.$API.Spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    async addSpuData(category3ID) {
      this.spu.category3Id = category3ID;
      let tradeMarkResult = await this.$API.Spu.reqTradeMarkList();
      if (tradeMarkResult.code == 200) {
        this.tradeMarkList.tradeMarkResult.data;
      }
      let saleResult = await this.$API.Spu.reqBaseSaleAttrList();
      if (saleResult.code == 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    cancel() {
      this.$emit("changeScene", { scene: 0, flag: "" });
      // Object.assign:合并对象,将参数二与参与一进行合并
      // Object.assign:将参数二
      // this._data:可以操作data中的响应式数据
      // this.$options:当前组件实例的配置对象,调用了data函数
      // 目前使用这一行函数会报错,未找到解决方法
      // Object.assign(this._data, this.$options.data());
      this.clearAllData();
    },
  },
  computed: {
    // 计算出还未选择的销售属性
    unSelectSaleAttr() {
      return this.saleAttrList.filter((item) => {
        // every函数:返回一个boolean值
        return this.spu.spuSaleAttrList.every((element) => {
          return item.name != element.saleAttrName;
        });
      });
    },
  },
};
</script>

<style  lang="scss">
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
